package com.xiaobao.campusLostFoundAfter.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/*分页插件配置*/
@Configuration
public class MyBatisConfig {

    /**
     * 配置 SqlSessionFactory Bean
     *
     * @param dataSource 数据源
     * @return SqlSessionFactory 实例
     * @throws Exception 如果创建过程中出现错误
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        // 创建并配置 MyBatis 的 Configuration 对象
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true); // 开启驼峰命名转换

        // 创建 SqlSessionFactoryBean 对象
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource); // 设置数据源
        factory.setConfiguration(configuration); // 应用配置

        // 添加分页插件
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        pageInterceptor.setProperties(properties);

        factory.setPlugins(pageInterceptor); // 设置插件

        // 指定 XML 映射文件的位置
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));

        // 返回 SqlSessionFactory 实例
        return factory.getObject();
    }
}